local meibu = fk.CreateSkill{
  name = "kl__meibu",
}


meibu:addEffect(fk.EventPhaseStart, {
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(meibu.name) and target.phase == Player.Play and
      target:inMyAttackRange(player) and not player:isNude()
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local card = room:askToDiscard(player, {
      min_num = 1,
      max_num = 1,
      include_equip = true,
      skill_name = meibu.name,
      prompt = "#kl__meibu-invoke::"..target.id,
      cancelable = true,
      skip = true,
    })
    if #card > 0 then
      event:setCostData(self, {tos = {target}, cards = card})
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local card = Fk:getCardById(event:getCostData(self).cards[1])
    room:addTableMarkIfNeed(player, "@kl__meibu_src-turn", card:getSuitString(true))
    if card.trueName ~= "slash" and not card.type == Card.TypeTrick then
      room:setPlayerMark(player, "kl__meibu_src-turn", 1)
    end
    room:throwCard(card, meibu.name, player, player)
    if target.dead then return end
    room:setPlayerMark(target, "kl__meibu-turn", 1)
    room:handleAddLoseSkills(target, "kl__zhixi")
    room.logic:getCurrentEvent():findParent(GameEvent.Turn):addCleaner(function()
      room:handleAddLoseSkills(target, "-kl__zhixi")
    end)
  end,
})
meibu:addEffect("distance", {
  fixed_func = function(self, from, to)
    if from:getMark("kl__meibu-turn") > 0 and to:getMark("kl__meibu_src-turn") > 0 then
      return 1
    end
  end,
})

meibu:addEffect(fk.AfterCardsMove, {
  anim_type = "drawcard",
  is_delay_effect = true,
  can_trigger = function(self, event, target, player, data)
    if player:getMark("@kl__meibu_src-turn") ~= 0 then
      for _, move in ipairs(data) do
        if move.skillName == "kl__zhixi" then
          for _, info in ipairs(move.moveInfo) do
            if table.contains(player:getTableMark("@kl__meibu_src-turn"), Fk:getCardById(info.cardId):getSuitString(true)) and
              player.room:getCardArea(info.cardId) == Card.DiscardPile then
              return true
            end
          end
        end
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local ids = {}
    for _, move in ipairs(data) do
      if move.skillName == "kl__zhixi" then
        for _, info in ipairs(move.moveInfo) do
          if table.contains(player:getTableMark("@kl__meibu_src-turn"), Fk:getCardById(info.cardId):getSuitString(true)) and
            player.room:getCardArea(info.cardId) == Card.DiscardPile then
            table.insertIfNeed(ids, info.cardId)
          end
        end
      end
    end
    player.room:moveCardTo(ids, Card.PlayerHand, player, fk.ReasonJustMove, meibu.name, nil, true, player)
  end,
})

return meibu
